﻿using System.Text;
using System.Collections.Specialized;
using Newtonsoft.Json;

namespace CometDocs
{
    internal partial class Client
    {
        /// <summary>
        /// Upload a file from public internet location to the CometDocs store: https://www.cometdocs.com/developer/apiDocumentation#method-uploadFileFromUrl
        /// </summary>
        /// <param name="token">A valid authentication token.</param>
        /// <param name="url">The URL of the file to upload.</param>
        /// <param name="name">The name to give to the uploaded file.</param>
        /// <param name="folderId">The folder in which the file will be uploaded or the root folder if unspecified.</param>
        /// <returns>A FileInfo instance representing the uploaded file.</returns>
        public FileInfo UploadFileFromUrl(AuthenticationToken token, string url, string name = null, long? folderId = null)
        {
            NameValueCollection @params = new NameValueCollection(4);
            @params.Add("token", token.Value);
            @params.Add("url", url);
            if (name != null)
            {
                @params.Add("name", name);
            }
            if (folderId != null)
            {
                @params.Add("folderId", folderId.ToString());
            }

            byte[] result = webClient.UploadValues(APIRoot + "uploadFileFromUrl", @params);

            string json = Encoding.ASCII.GetString(result);

            UploadFileFromUrlResponse response = JsonConvert.DeserializeObject<UploadFileFromUrlResponse>(json);

            CheckAndThrow(response);

            return response.File;
        }

        /// <summary>
        /// <see cref="UploadFileFromUrl(AuthenticationToken, string, Folder)"/>
        /// </summary>
        /// <param name="token"></param>
        /// <param name="url"></param>
        /// <param name="folder"></param>
        /// <returns></returns>
        public FileInfo UploadFileFromUrl(AuthenticationToken token, string url, FolderInfo folder)
        {
            return UploadFileFromUrl(token, url, null, folder.ID);
        }
    }
}
